package com.th.service.impl;

import com.th.common.exception.BaseServiceException;
import com.th.file.service.FileStorageService;
import com.th.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author ErrorRua
 * @date 2023/06/22
 * @description:
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileStorageService fileStorageService;

    @Value("${minio.readPath}")
    private String readPath;

    @Value("${minio.prefix}")
    private String prefix;

    @Override
    public String uploadFile(MultipartFile file) {

        String filename = UUID.randomUUID() + file.getOriginalFilename();

        try {
            String stored = fileStorageService.store(prefix, filename, file.getContentType(), file.getInputStream());

            return readPath + stored;
        } catch (IOException e) {
            throw new BaseServiceException(500, "文件上传失败");
        }

    }

    @Override
    public void deleteFile(String filePath) {
        String[] split = filePath.split(readPath);
        String path = split[1];
        fileStorageService.delete(path);
    }
}
